package com.itsu.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itsu.dao.CatalogDao;
import com.itsu.dao.CompanyDao;
import com.itsu.domain.Catalog;
import com.itsu.domain.Company;
import com.itsu.service.CatalogService;
import com.itsu.utils.MapperUtils;

import java.util.List;

public class CatalogServiceImpl implements CatalogService {

    private CatalogDao mapper;

    @Override
    public void save(Catalog catalog) {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            mapper.save(catalog);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void delete(Catalog catalog) {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            mapper.delete(catalog);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void update(Catalog catalog) {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            mapper.update(catalog);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public Catalog findById(String id) {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            Catalog catalog = mapper.findById(id);
            return catalog;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public List<Catalog> findAll() {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            List<Catalog> catalogList = mapper.findAll();
            return catalogList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public PageInfo<Catalog> findAll(int pageNum, int pageSize) {
        try {
            mapper = MapperUtils.getMapper(CatalogDao.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Catalog> all = mapper.findAll();
            PageInfo<Catalog> catalogPageInfo = new PageInfo<>(all);
            return catalogPageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }
}
